<route lang="json5">
  {
    style: {
      navigationBarTitleText: '添加地址',
    },
  }
  </route>
<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <view class="form-label">收货人</view>
        <input class="form-input" type="text" v-model="formData.name" placeholder="请填写收货人姓名"
          placeholder-class="placeholder" />
      </view>

      <view class="form-item">
        <view class="form-label">手机号</view>
        <input class="form-input" type="text" v-model="formData.phone" placeholder="请输入手机号"
          placeholder-class="placeholder" maxlength="11" />
      </view>

      <view class="form-item">
        <view class="form-label">省市区</view>
        <view class="form-select">

          <picker mode="multiSelector" @change="handleRegionChange" @columnchange="handleColumnChange"
            :value="regionIndex" :range="regionArray" :range-key="'name'" class="flex-1">
            <view class="flex-1 text-gray-400" :class="{ 'text-gray-900': formData.area }">{{ formData.area || '请选择所在地'
              }}
            </view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <view class="form-label">详细地址</view>
        <input class="form-input" type="text" v-model="formData.address" placeholder="请输入详细地址"
          placeholder-class="placeholder" />
      </view>
    </view>

    <view class="setting">
      <view class="setting-item">
        <text>设为默认地址</text>
        <switch :checked="formData.is_default" @change="handleDefaultChange" color="#1890ff" />
      </view>
    </view>

    <view class="footer">
      <button class="save-btn w-80 mx-auto" @click="handleSave">保存</button>
    </view>



  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { getAddressInfoAPI, postAddressEditAPI, getRegion } from '@/service/index'
import { useRoute } from 'vue-router'

const formData = reactive({
  id: 0,
  name: '',
  phone: '',
  province_id: 0,
  city_id: 0,
  district_id: 0,
  address: '',
  is_default: 0,
  lat: "0.",
  lng: "0",
  province_name: "",
  city_name: "",
  district_name: "",
  pid: 0,
  cid: 0,
  aid: 0,
  detail: '',
  area: '',
  cont: ''
})



// 区域选择相关数据
const regionData = ref([])
const regionArray = ref([[], [], []]) // 三维数组，分别是省、市、区
const regionIndex = ref([0, 0, 0]) // 当前选择的省市区下标

// 处理区域数据
const getRegionData = async () => {
  const res = await getRegion()
  if (res.code === 1 && res.data) {
    regionData.value = res.data
    // 初始化省份列表
    regionArray.value[0] = res.data
    // 初始化第一个省份的城市列表
    if (res.data[0]?.children) {
      regionArray.value[1] = res.data[0].children
      // 初始化第一个城市的区列表
      if (res.data[0].children[0]?.children) {
        regionArray.value[2] = res.data[0].children[0].children
      }
    }
  }
  console.log('regionArray', regionArray.value)
}

// 处理列变化
const handleColumnChange = (e: any) => {
  const column = e.detail.column
  const value = e.detail.value

  if (column === 0) { // 切换省份时更新城市和区列表
    regionIndex.value[0] = value
    regionIndex.value[1] = 0
    regionIndex.value[2] = 0
    if (regionData.value[value]?.children) {
      regionArray.value[1] = regionData.value[value].children
      if (regionData.value[value].children[0]?.children) {
        regionArray.value[2] = regionData.value[value].children[0].children
      } else {
        regionArray.value[2] = []
      }
    }
  } else if (column === 1) { // 切换城市时更新区列表
    regionIndex.value[1] = value
    regionIndex.value[2] = 0
    const provinceData = regionData.value[regionIndex.value[0]]
    if (provinceData?.children[value]?.children) {
      regionArray.value[2] = provinceData.children[value].children
    } else {
      regionArray.value[2] = []
    }
  }
}

// 处理区域选择
const handleRegionChange = (e: any) => {
  const values = e.detail.value
  const province = regionArray.value[0][values[0]]
  const city = regionArray.value[1][values[1]]
  const district = regionArray.value[2][values[2]]

  formData.area = `${province.name} ${city.name} ${district?.name || ''}`
  formData.province_id = province.id
  formData.city_id = city.id
  formData.district_id = district?.id || 0
  regionIndex.value = values
}

const handleDefaultChange = (e: any) => {
  formData.is_default = e.detail.value ? 1 : 0
}








const handleSave = () => {
  console.log('formData', formData)

  formData.pid = formData.province_id
  formData.cid = formData.city_id
  formData.aid = formData.district_id

  if (!formData.name) {
    uni.showToast({
      title: '请填写收货人姓名',
      icon: 'none',
    })
    return
  }
  if (!formData.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    })
    return
  }
  if (!formData.pid || !formData.cid || !formData.aid) {
    uni.showToast({
      title: '请选择省市区',
      icon: 'none',
    })
    return
  }
  if (!formData.address) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none',
    })
    return
  }
  formData.detail = formData.address

  // console.log('formData',formData)
  // return

  postAddressEditAPI(formData).then((res) => {
    if (res.code === 1) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      })
      uni.navigateBack()
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  })
}


const id = ref();
const getAddressDetail = () => {
  getAddressInfoAPI({ id: id.value }).then((res) => {
    const addressData = res.data
    formData.id = addressData.id
    formData.name = addressData.name
    formData.phone = addressData.phone
    formData.area = `${addressData.province_name} ${addressData.city_name} ${addressData.district_name}`.trim()
    formData.province_id = addressData.pid
    formData.city_id = addressData.cid
    formData.district_id = addressData.aid
    formData.address = addressData.address
    formData.is_default = addressData.is_default
  })
}

//#ifdef APP-PLUS || MP-WEIXIN
onLoad((options) => {
  if (options.id) {
    id.value = options.id
    getAddressDetail()
  }
  getRegionData()

})
onShow(() => {
  if (options.id) {
    id.value = options.id
    getAddressDetail()
  }
  getRegionData()
})
//#endif

//#ifdef H5
onMounted(() => {
  const route = useRoute()
  id.value = route.query.id
  if (id.value) {
    getAddressDetail()

  }
  getRegionData()
})

//#endif
</script>

<style>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.form {
  padding: 0 32rpx;
  margin-top: 20rpx;
  background-color: #ffffff;
}

.form-item {
  display: flex;
  align-items: center;
  min-height: 100rpx;
  border-bottom: 1px solid #eeeeee;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 140rpx;
  font-size: 14px;
  color: #333333;
}

.form-input {
  flex: 1;
  font-size: 14px;
  color: #333333;
}

.form-select {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
}

.select-text {
  font-size: 14px;
  color: #333333;
}

.placeholder {
  color: #999999;
}

.setting {
  padding: 0 32rpx;
  margin-top: 20rpx;
  background-color: #ffffff;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  font-size: 14px;
  color: #333333;
}

.footer {
  padding: 40rpx 32rpx;
  margin-top: auto;
}

.save-btn {
  height: 88rpx;
  font-size: 16px;
  line-height: 88rpx;
  color: #ffffff;
  text-align: center;
  background: #1890ff;
  border-radius: 44rpx;
}

.region-popup {
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
}

.region-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
  border-bottom: 1px solid #eeeeee;
}

.region-header .cancel {
  font-size: 14px;
  color: #999999;
}

.region-header .title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.region-header .confirm {
  font-size: 14px;
  color: #ff6a00;
}

.region-picker {
  width: 100%;
  height: 480rpx;
}

.picker-item {
  font-size: 14px;
  line-height: 80rpx;
  color: #333333;
  text-align: center;
}
</style>
